package com.jf.docsify.common.init.db;

import java.io.FileOutputStream;
import java.io.FileWriter;
import java.net.URL;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.lang3.ClassUtils;

import com.jf.docsify.common.annotation.DbType;
import com.jf.docsify.common.enums.EnumDbType;
import com.jf.docsify.common.exception.DocsifyException;
import com.jf.docsify.common.utils.ClassUtil;
import com.jfinal.aop.Aop;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;

public class DbInitFactory {

    public void init(String dbType) {
        init(EnumDbType.getType(dbType));
    }

    public void init(EnumDbType dbType) {
        try {
            String packageName = ClassUtils.getPackageName(DbInitFactory.class);
            Set<Class<?>> classes = ClassUtil.getClasses(packageName);
            Iterator<Class<?>> iterator = classes.iterator();
            while (iterator.hasNext()) {
                Class<?> clazz = iterator.next();
                DbType annotation = clazz.getAnnotation(DbType.class);
                if (annotation == null) {
                    continue;
                }
                EnumDbType value = annotation.value();
                if (value.equals(dbType)) {
                    DbInitService dbInit = (DbInitService) Aop.get(clazz);
                    dbInit.process();
                    return;
                }
            }
        } catch (Exception e) {
            DocsifyException.throwE(e);
        }
    }


    private ClassLoader getClassLoader() {
        ClassLoader ret = Thread.currentThread().getContextClassLoader();
        return ret != null ? ret : this.getClass().getClassLoader();
    }

    public void saveDisabled(String configName) {
        try {
            URL resource = getClassLoader().getResource(configName);
            Prop prop = PropKit.getProp(configName);
            Properties properties = prop.getProperties();
            properties.setProperty("db.init.enable", "false");
            properties.store(new FileOutputStream(resource.getFile()), null);
            PropKit.append(prop);
        } catch (Exception e) {
            DocsifyException.throwE("设置 开启自动初始化数据库表 参数异常", e);
        }
    }
}
